<template>
  <view
    :style="imgWidthStr"
  >
    <image
      :style="imgWidthStr"
      :src="qrCodeImg"
    />
  </view>
</template>

<script>
import QR from '@/utils/wxqrcode.js'
export default {
  name: 'Index',
  props: {
    imgWidth: {
      type: Number,
      default: 0
    },
    qrCodeInfo: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      qrCodeImg: '',
      // qrCodeInfo: 'www.baidu.com',
      // qrCodeSize: 200,
    }
  },
  computed: {
    imgWidthStr() {
      return 'width: ' + this.imgWidth + 'rpx;height: ' + this.imgWidth + 'rpx;';
    },
    curQrCodeInfo() {
      return this.qrCodeInfo;
    },
  },
  watch: {
    curQrCodeInfo(newValue, oldValue) {
      this.createQrCodeFn()
    }
  },
  mounted() {
    this.createQrCodeFn()
  },
  methods: {
    createQrCodeFn() {
      this.qrCodeImg = QR.createQrCodeImg(this.curQrCodeInfo, {
        errorCorrectLevel: 'M',
        typeNumber: 2
      })
    },
    /*保存图片*/
    longPressFn() {
      uni.getSetting({
        success(res) {
          let writePhotosAlbumAuth = ''
          // #ifdef MP-WEIXIN
          writePhotosAlbumAuth = res.authSetting['scope.writePhotosAlbum']
          // #endif
          // #ifdef MP-ALIPAY
          writePhotosAlbumAuth = res.authSetting.writePhotosAlbum
          // #endif
          // 判断是否有权限
          if (writePhotosAlbumAuth) {
            return;
          }
          if (!writePhotosAlbumAuth) {
            // 打开权限设置页面
            uni.openSetting({
              success(res) {
                if (res.authSetting['scope.writePhotosAlbum']) {
                  this.saveImgFn()
                }
              }
            })
            return
          }
        }
      });
      this.saveImgFn()
    },
    saveImgFn() {
      // #ifdef MP-WEIXIN
      const userDataPath = wx.env.USER_DATA_PATH
      const base64Image = this.qrCodeImg // 后台返回的base64数据
      const imgData = base64Image.replace(/[\r\n]/g, '') // 将回车换行换为空字符''
      const fileSystemManager = wx.getFileSystemManager();
      const number = Math.random();
      fileSystemManager.writeFile({
        filePath: userDataPath + '/pic' + number + '.png',
        data: imgData.slice(22),
        encoding: 'base64',
        success: res => {
          this.saveImageToPhotosAlbum(userDataPath + '/pic' + number + '.png');
        }, fail: err => {
          this.$u.toast(err.errMsg)
        }
      })
      // #endif
      // #ifdef MP-ALIPAY
      this.saveImageToPhotosAlbum(this.qrCodeImg);
      // #endif
    },
    saveImageToPhotosAlbum(imgUrl) {
      const that = this;
      uni.saveImageToPhotosAlbum({
        filePath: imgUrl,
        success: function() {
          that.$u.toast('保存成功')
        },
        fail: function() {
          that.$u.toast('保存失败')
        }
      });
    }
  }
}
</script>

<style scoped>

</style>
